package com.ytd.smartcanteen.weighting.util;

import android.app.AlarmManager;
import android.content.Context;
import android.os.PowerManager;

import com.ytd.common.util.FormatUtil;
import com.ytd.common.util.LogUtil;
import com.ytd.common.util.ThreadUtil;
import com.ytd.common.util.TimerManager;
import com.ytd.common.util.YtdConfig;
import com.ytd.smartcanteen.weighting.WeightingApplication;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Date;

/**
 * 定时开关机工具类
 *
 * @author gaoguanchao
 * @since 2023/10/13 0013
 */
public class ShutdownUtil {
    public static void setDeviceOff() {
        //检测是否设置
        boolean scheduleSwitchEnabled = YtdConfig.getScheduleSwitchEnabled();
        if (!scheduleSwitchEnabled) {
            return;
        }
        ThreadUtil.execute(() -> {
            //判断时间是否已到定时关机时间
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            Calendar shutdown = Calendar.getInstance();
            Date firstShutdownTime = TimerManager.getInstance().getFirstShutdownTime();
            if (firstShutdownTime == null) {
                return;
            }
            shutdown.setTime(firstShutdownTime);

            long shutdownTime = WeightConfig.getShutdownTime();
            Calendar lastShutdownTime = Calendar.getInstance();
            lastShutdownTime.setTime(new Date(shutdownTime));

            Calendar clone = (Calendar) lastShutdownTime.clone();
            clone.add(Calendar.MINUTE, 1);

            if (shutdown.compareTo(calendar) == 0 || lastShutdownTime.compareTo(calendar) == 0 ||
                    clone.compareTo(calendar) == 0) {//到达时间出现关机提示弹窗
                WeightConfig.setShutdownTime(calendar.getTime().getTime());
                shutdown();
            }
        });
    }

    public static void setDeviceOn() {
        //检测是否设置
        boolean scheduleSwitchEnabled = YtdConfig.getScheduleSwitchEnabled();
        if (!scheduleSwitchEnabled) {
            if (YtdConfig.getStartTime() > System.currentTimeMillis()) {
                closeRtcAlarm(YtdConfig.getStartTime());
                YtdConfig.setStartTime(0);
            }
            return;
        }
        if (YtdConfig.getStartTime() > System.currentTimeMillis()) {
            return;
        }
        ThreadUtil.execute(() -> {
            //检测是否已设置
            long readRtcAlarm = readRtcAlarm();
            Calendar readAlarm = Calendar.getInstance();
            readAlarm.setTime(new Date(readRtcAlarm * 1000));
            LogUtil.d("readAlarm：" + FormatUtil.getDateFormat(readAlarm.getTime()));
            Date firstStartupTime = TimerManager.getInstance().getFirstStartupTime();
            if (firstStartupTime == null) {
                return;
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(firstStartupTime);

            if (readAlarm.compareTo(calendar) == 0) {
                if (YtdConfig.getStartTime() == 0) {
                    YtdConfig.setStartTime(calendar.getTime().getTime());
                }
                return;
            }
            long time1 = firstStartupTime.getTime();
            int result = updateRtcAlarm(time1);
            if (result == 0) {
                YtdConfig.setStartTime(time1);
                LogUtil.d("设置开机时间：" + FormatUtil.getDateFormat(firstStartupTime) + "----result:" + result);
            } else {
                LogUtil.d("设置开机时间失败 result:" + result);
            }
        });

    }

    private synchronized static int updateRtcAlarm(long time) {
        LogUtil.d("updateRtcAlarm:" + time);
        AlarmManager alarmManager =
                (AlarmManager) WeightingApplication.getContext().getSystemService(Context.ALARM_SERVICE);
        Method updateRtcAlarm;
        try {
            updateRtcAlarm = alarmManager.getClass().getDeclaredMethod("updateRtcAlarm", boolean.class, long.class);
        } catch (NoSuchMethodException e) {
            return -1;
        }
        try {
            updateRtcAlarm.invoke(alarmManager, true, time);
        } catch (IllegalAccessException | InvocationTargetException e) {
            return -2;
        }
        return 0;
    }

    private synchronized static void closeRtcAlarm(long time) {
        LogUtil.d("closeRtcAlarm");
        AlarmManager alarmManager =
                (AlarmManager) WeightingApplication.getContext().getSystemService(Context.ALARM_SERVICE);
        Method updateRtcAlarm;
        try {
            updateRtcAlarm = alarmManager.getClass().getDeclaredMethod("updateRtcAlarm", boolean.class, long.class);
        } catch (NoSuchMethodException e) {
            return;
        }
        try {
            updateRtcAlarm.invoke(alarmManager, false, time);
        } catch (IllegalAccessException | InvocationTargetException ignored) {
        }
    }

    private synchronized static long readRtcAlarm() {
        AlarmManager alarmManager =
                (AlarmManager) WeightingApplication.getContext().getSystemService(Context.ALARM_SERVICE);
        Method readRtcAlarm;
        try {
            readRtcAlarm = AlarmManager.class.getDeclaredMethod("readRtcAlarm");
        } catch (NoSuchMethodException e) {
            return -2;
        }
        try {
            Long time = (Long) readRtcAlarm.invoke(alarmManager);
            return time == null ? 0 : time;
        } catch (IllegalAccessException | InvocationTargetException e) {
            return -1;
        }
    }

    private static void shutdown() {
        //弹窗倒计时结束时，关机
        try {
            PowerManager pManager =
                    (PowerManager) WeightingApplication.getContext().getSystemService(Context.POWER_SERVICE);
            if (pManager != null) {
                Method method =
                        pManager.getClass().getMethod("shutdown", boolean.class, String.class, boolean.class);
                method.invoke(pManager, false, null, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        //        try {
//            Runtime.getRuntime().exec("reboot -p"); //关机
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }
}
